<?php

	// ---------------------------
	// Set global vars
	// ---------------------------
	
	$dbHost = "localhost";
	$dbUser = "fixme";
	$dbPass = "fixme";
	$dbName = "fixme";
	$dbPrefix = "wu_";

	// ---------------------------
	// Verify the user agent
	// ---------------------------

	if($_SERVER['HTTP_USER_AGENT'] != "WattsUp.NET"){
		die("User error.");
	}

	// ---------------------------
	// Parse and verify we got the required POST params
	// ---------------------------
	
	// Parse
	$meterId = $_POST['id'];
	$watts = $_POST['w'];
	$sendRate = $_POST['sr'];
	
	// Verify
	if( ($meterId == "") || ($watts == "") || ($sendRate == "") ){
		die("Invalid parameters.");
	}

	// ---------------------------
	// Return the relay status [0] and optional send rate
	// ---------------------------
	
	// Build returncode
	$returnCode = "[0";
	if($sendRate != "1"){
		$returnCode .= "!1";
	}
	$returnCode .= "]";
	
	// Send
	echo $returnCode;

	// ---------------------------
	// Connect to the db
	// ---------------------------
	
	// Open MySQL connection
	mysql_connect($dbServer, $dbUser, $dbPass) or die(mysql_error());
	
	// Select our db
	mysql_select_db($dbName) or die(mysql_error());
	
	// ---------------------------
	// Non-destructive table create
	// ---------------------------
	
	// See if it exists
	if(!mysql_num_rows(mysql_query("SHOW TABLES LIKE '" . $dbPrefix . "power_samples';"))){
	
		// Create
		mysql_query("CREATE TABLE " . $dbPrefix . "power_samples( sample_id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(sample_id), meter_id INT, watts INT, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");
	
	}

	// ---------------------------
	// Insert
	// ---------------------------
	
	// Insert
	mysql_query("INSERT INTO " . $dbPrefix . "power_samples (meter_id, watts) VALUES('" . $meterId . "', '" . $watts . "');");		
	
	// ---------------------------
	// Disconnect from the db
	// ---------------------------
	
	// Close MySQL connection
	mysql_close();

?>